import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/page/help_page.dart';
import '../entity/borrow_again_entity.dart';
import '../entity/reader_entity.dart';
import '../http/api.dart';
import '../main.dart';
import '../util/camera_util.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/circle_progress_widget.dart';
import '../widget/clipper.dart';
import '../widget/device_name_widget.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'dart:ui' as ui;

class Mine extends StatefulWidget {
  const Mine({Key? key}) : super(key: key);

  @override
  State<Mine> createState() => _MineState();
}

class _MineState extends State<Mine> {

  RxBool preview = RxBool(false);
  Timer? _timer;
  RxBool isEmpty = RxBool(false);

  late List<ReaderCurrentBorrowList> _lists;
  final RxList<ReaderCurrentBorrowList> _list = RxList();
  var pageIndex = 1;
  var pageSize = 4;

  late ReaderEntity readerEntity;
  CameraUtil camera = CameraUtil();

  RxBool showCamara = false.obs;


  @override
  initState() {
    super.initState();

    readerEntity = Get.arguments;
    if(readerEntity.currentBorrowList != null ){
      _lists = readerEntity.currentBorrowList!;
      _subList();
    }

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.normal,(){
        if(Get.isDialogOpen != null && Get.isDialogOpen!){
          Get.back();
        }
        currentTask.clear();
        Get.back();
      });
    });

    _checkFace();
  }

  _subList(){
    if(pageIndex<1){
      pageIndex = 1;
      toastWarn("已经是第一页");
    }
    if(_lists.length > pageIndex*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,pageIndex*pageSize));
    }else if(_lists.length <= pageIndex*pageSize && _lists.length > (pageIndex-1)*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,_lists.length));
    }else{
      pageIndex--;
      toastWarn("已经是最后一页");
    }
  }

  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          InkWell(
            onTap: (){
              Get.to(()=> const Help());
            },
            child:  Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )
        ],
      ),
    );
  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              currentTask.clear();
              timer.cancel();
              Get.back();
            },
            child: _image("assets/images/back.png",60.w,23.h),
          ),
          _image("assets/images/mine.png",42.w,21.h),
          Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
        ],
      )
    );
  }

  _personInfo(){
    return Container(
        height: 110.h,
        decoration:const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/person_info_bg.png",
            ),
          ),
        ),
        margin: EdgeInsets.only(top: 10.h,left: 20.w,right: 20.w),
        padding: EdgeInsets.only(left: 30.w,right: 30.w),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              left: 0,
              child: _image("assets/images/head.jpg", 50.w, 50.w),
            ),
            Positioned(
              left: 60.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(readerEntity.name??'',style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold,fontSize: 12.sp),),
                  SizedBox(height: 3.h,),
                  Text('读者证号:${readerEntity.no}',style: TextStyle(color: Colors.blue,fontSize: 8.sp)),
                  SizedBox(height: 3.h,),
                  if(settingEntity.face != 'kd')...[
                    InkWell(
                        onTap: () async {
                          if(showCamara.value){
                            return;
                          }
                          showCamara.value = true;
                          if(camera.cameraId.value == -1){
                            camera.cameraId.value = await camera.openCamera();
                          }

                          if(camera.cameraId.value != -1){
                            _start();
                            if(preview.value){
                              preview.value = false;
                              await CameraPlatform.instance.resumePreview(camera.cameraId.value);
                            }
                          }

                        },
                        child: Obx(() => isEmpty.value?
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("人脸登陆:已注册 ",style: TextStyle(color: Colors.blue,fontSize: 8.sp),),
                            Image.asset("assets/images/camera_change.png",width: 30.w,fit: BoxFit.fitWidth,),
                          ],
                        ):
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("人脸登陆:未注册 ",style: TextStyle(color: Colors.blue,fontSize: 8.sp),),
                            Image.asset("assets/images/camera_register.png",width: 30.w,fit: BoxFit.fitWidth,),
                          ],
                        ),
                        )
                    ),
                  ]

                ],
              ),
            ),
            Positioned(
                right: 0,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    CircleProgress(size: 60.w,strokeWidth: 3.w,percent: readerEntity.currentBorrowCount!/readerEntity.limitCount!,color: Colors.blue,),
                    Container(
                      width: 50.w,
                      height: 50.w,
                      decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.all(Radius.circular(25.r)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text('${readerEntity.currentBorrowCount}/${readerEntity.limitCount}',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
                          Text('借阅数量',style: TextStyle(color: Colors.white,fontSize: 6.sp),)
                        ],
                      ),
                    )
                  ],
                )
            ),

          ],
        )
    );
  }


  _itemBuilder(index){
    var item = _list[index];

    return Container(
      height: 90.h,
      alignment: Alignment.center,
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              item.status==1?"assets/images/person_book_bg_green.png":item.overdue==false?"assets/images/person_book_bg_blue.png":"assets/images/person_book_bg_red.png"
            ),
          )
        ),
      child: Stack(
        children: [
          Positioned(
            top: 15.h,
            left: 15.w,
            right: 75.w,
            child: Text('${item.bookTitle}',maxLines:1,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 10.sp,fontWeight: FontWeight.bold),),
          ),
          Positioned(
            top: 36.h,
            left: 15.w,
            child: Text('图书编号: ${item.bookNo}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),
          ),
          Positioned(
            top: 49.h,
            left: 15.w,
            child: Text('归还时间: ${item.readyReturnDate}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),
          ),
          Positioned(
            top: 62.h,
            left: 15.w,
            child: Text(item.error != null?'提示信息: ${item.error}':'',style: TextStyle(color: Colors.red,fontSize: 8.sp),),
          ),

          Positioned(
            top: 9.5.h,
            right: 24.w,
            child: Text(item.status==1?'已续借':item.overdue==false?'已借阅':'已超时',style: TextStyle(color: Colors.white, fontSize: 10.sp),),
          ),

          Positioned(
            bottom: 10.h,
            right: 10.w,
            child: InkWell(
              onTap: (){
                if(item.status==0){
                  _borrowAgain(item);
                }
              },
              child: _image(item.status==1?"assets/images/borrow_success.png":"assets/images/borrow_again.png", 60.w, 27.h),
            )
          ),

        ],
      )
    );
  }

  _borrowAgain(ReaderCurrentBorrowList item) async {
    var res = await bookBorrowAgain(currentTask.uid, item.bookNo);
    BorrowAgainEntity? data = res.$1;
    if(data != null){
      var index = _list.indexOf(item);
      _list.remove(item);
      item.status = 1;
      item.readyReturnDate = data.readyReturnDate;
      _list.insert(index, item);
    }else{
      var index = _list.indexOf(item);
      _list.remove(item);
      item.error = res.$2;
      _list.insert(index, item);
    }
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 20.w,right: 20.w),
      height: 380.h,
      child: Obx(() => ListView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: _list.length,
      )),
    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: (){
            pageIndex--;
            _subList();
          },
          child: _image("assets/images/previous_blue.png", 80.w, 36.h),
        ),
        InkWell(
          onTap: (){
            pageIndex++;
            _subList();
          },
          child: _image("assets/images/next_blue.png", 80.w, 36.h),
        )
      ],
    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }

  _start(){
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      _widgetToImage();

    });
  }

  final GlobalKey _globalKey = GlobalKey();

  _widgetToImage() {
    if(_globalKey.currentContext == null){
      _timer?.cancel();
      _timer = null;
      return;
    }
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";
          faceAdd(currentTask.uid,currentTask.uName,base64Image).then((data){
            if(data.$1 ){
              toastWarn('认证成功');
              tts.speak("认证成功");
              _timer?.cancel();
              _timer = null;
              CameraPlatform.instance.pausePreview(camera.cameraId.value).then((value){
                preview.value = true;
              });

            }else{
              toastWarn('${data.$2}');
            }
          });
        }
      });
    });
  }

  _checkFace() {
    if(settingEntity.face != 'kd'){
      faceQuery(readerEntity.no!).then((value){
        isEmpty.value = value;
      });
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  _cameraWidget(){
    return Obx(() => Stack(
      // alignment: AlignmentDirectional.center,
      children: [
        if(camera.cameraId.value > 0)...[
          RepaintBoundary(
            key: _globalKey,
            child:  ClipOval(
              clipper: ClipperOvalPath(),
              child:  Transform.scale(
                scale:settingEntity.scale2??2.5,
                child: Transform.translate(offset: Offset((settingEntity.translateX2??0).w,(settingEntity.translateY2??-20).h),
                  child: RotatedBox(
                    quarterTurns: 0,
                    child: AspectRatio(
                        aspectRatio: camera.getPreviewSize(),
                        child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                    ),
                  ),),
              ),
            ),
          )
        ],
        Positioned(top:280.h,left:0,right:0,child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              child: Image.asset("assets/images/${preview.value?'result_confirm.jpg':'camera_cancel.png'}", width: 80.w, fit: BoxFit.fitWidth,),
              onTap: (){
                showCamara.value = false;
                _timer?.cancel();
                _timer = null;
                if(preview.value){
                  _checkFace();
                }
              },
            ),
            if(preview.value)...[
              SizedBox(height: 10.h,),
              InkWell(
                child:  Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),
                onTap: () async {
                  preview.value = false;
                  await CameraPlatform.instance.resumePreview(camera.cameraId.value);
                  _start();
                },
              )
            ]

          ],
        )),
        // Positioned(top:280.h,child: Align(child: InkWell(
        //   child: Image.asset("assets/images/${preview.value?'result_confirm.jpg':'camera_cancel.png'}", width: 80.w, fit: BoxFit.fitWidth,),
        //   onTap: (){
        //     _disposeCurrentCamera();
        //     if(preview.value){
        //       _checkFace();
        //     }
        //   },
        // ),)),
        // if(preview.value)...[
        //   Positioned(top:340.h,child:  Align(child: InkWell(
        //     child:  Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),
        //     onTap: () async {
        //       preview.value = false;
        //       await CameraPlatform.instance.resumePreview(cameraId.value);
        //       _start();
        //     },
        //   ),))
        // ]
      ],
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage(
                  "assets/images/bg.png",
                ),
              ),
            ),
            child: Container(
              margin: EdgeInsets.only(top: 160.h),
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
            ),
          ),
          Positioned(
              top: 0.h,
              left: 0,
              right: 0,
              child: _appBar(),
          ),
          Positioned(
              top: 42.h,
              left: 0,
              right: 0,
              child: _title(),
          ),
          Positioned(
              top: 86.h,
              left: 0,
              right: 0,
              child: _personInfo(),
          ),
          Positioned(
              top: 200.h,
              left: 0,
              right: 0,
              child: _booksContainer(),
          ),
          Positioned(
            top: 578.h,
            left: 0,
            right: 0,
            child: _action()
          ),

          Positioned(
            top: 200.h,
            bottom: 0,
            left: 0,
            right: 0,
            child: Obx(() => Visibility(visible:camera.cameraId.value > 0 && showCamara.value,child: Container(
              decoration: const BoxDecoration(
                color: Colors.white
              ),
              child:  _cameraWidget(),
            ))),
          )
        ],
      )
    );
  }
}

